#!/usr/bin/python2
# -*- coding: utf-8 -*-

import sys,os,xmpp,time,select,string,re
import db_oper

class Bot:

    def __init__(self,jabber):
        self.jabber = jabber
       # self.remotejid = remotejid

    def register_handlers(self):
        self.jabber.RegisterHandler('message',self.xmpp_message)
        self.jabber.RegisterHandler('presence', self.authRoster, typ='subscribe')

    def xmpp_message(self, con, event):
        type = event.getType()
        fromjid = event.getFrom().getStripped()
        #if type in ['message', 'chat', None] and fromjid == self.remotejid:
        if event.getBody() != None:
            body = event.getBody()
            sys.stdout.write(body.encode('utf-8') + '\n')
            if re.match("(!пары [1-9]{2} [1-2])", body[:10].encode('utf-8')):
            #if body.lower()[:5] == u'!пары':
                days = {'пн': 1, 'вт': 2, 'ср': 3, 'чт': 4, 'пт': 5, 'сб': 6}
                grp = int(body[6:8])
                sub_grp = int(body[9:10])
                day = body[11:13].encode('utf-8')
                num = 0
                if day: num = days[day]
                msg = xmpp.protocol.Message(to=fromjid,body=db_oper.get_schedule(grp, sub_grp, num),typ='chat')
                self.jabber.send(msg)
            else:
                msg = xmpp.protocol.Message(to=fromjid,body='Мне Вам нечего показать, возможно Вы допустили ошибку при вводе запроса.',typ='chat')
                self.jabber.send(msg)

        
    def authRoster(self, conn, msg):
        r = self.jabber.getRoster()
        x = msg.getFrom()
        r.Authorize(x)
        r.Subscribe(x)

    def stdio_message(self, message):
        m = xmpp.protocol.Message(to=self.remotejid,body=message,typ='chat')
        self.jabber.send(m)
        pass

    def xmpp_connect(self):
        con=self.jabber.connect()
        if not con:
            sys.stderr.write('could not connect!\n')
            return False
        sys.stderr.write('connected with %s\n'%con)
        auth=self.jabber.auth(jid.getNode(),jidparams['password'],resource=jid.getResource(), sasl=1)
        if not auth:
            sys.stderr.write('could not authenticate!\n')
            return False
        sys.stderr.write('authenticated using %s\n'%auth)
        self.jabber.sendInitPresence()
        self.register_handlers()
        return con

if __name__ == '__main__':

    #tojid="sirius_gs@jabber.ru"
    jidparams = {'jid': "schedulebot@jabber.ru", 'password': "Oy2e3L8"}
    #jidparams = {'jid': "megabot@zloiia.ath.cx/suka", 'password': "qwerty123"}
    
    jid=xmpp.protocol.JID(jidparams['jid'])
    cl=xmpp.Client(jid.getDomain(),debug=[])
    
    bot=Bot(cl)

    if not bot.xmpp_connect():
        sys.stderr.write("Could not connect to server, or password mismatch!\n")
        sys.exit(1)

    #cl.SendInitPresence(requestRoster=0)   # you may need to uncomment this for old server
    
    socketlist = {cl.Connection._sock:'xmpp',sys.stdin:'stdio'}
    online = 1

    while online:
        cl.Process(1)
    cl.disconnect()
